package com.qyl.honghengshop.dao;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class BaseDao {

	private static SqlSessionFactory sqlSessionFactory;
	private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
	
	static{
		
		try {
			InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		} catch (IOException e) {
			System.out.println("连接数据库出错");
			e.printStackTrace();
		}
	}
	//获得sqlsession方法
	public SqlSession getSqlSession(){
		
		SqlSession sqlSession = threadLocal.get();
		
		if(sqlSession == null){
			sqlSession = sqlSessionFactory.openSession();
		}
		threadLocal.set(sqlSession);
		return sqlSession;
	}
	
	//关闭sqlsession方法
	public void closeSqlSession(){
		SqlSession sqlSession = threadLocal.get();
		
		if(sqlSession != null){
			sqlSession.close();
		}
		threadLocal.remove();
		
	}
}
